//
//  googleCodeViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/10/27.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyUserDefaults

class googleCodeViewController: BaseViewController {
    var myCode : String!
    override func viewDidLoad() {
        super.viewDidLoad()
        layoutNav()
        makeBaseUI()
        // Do any additional setup after loading the view.
    }
    
    func layoutNav(){
        self.title = XALanguageManager.getString(key: "谷歌账户验证")
    }
    
    func makeBaseUI() {
        self.view.backgroundColor = UIColor("#EEF0F7")
        let topImageView = UIImageView(frame: CGRect(x: 75*_kScreenWidth/2, y: 100*_kScreenWidth, width: 300*_kScreenWidth, height: 48*_kScreenWidth))
        topImageView.image = UIImage.init(named: "")
        self.view.addSubview(topImageView)
        
        let bottombackView = UIImageView(image: UIImage.init(named: "矢量智能对象@2x"))
        self.view.addSubview(bottombackView)
        bottombackView.snp.makeConstraints { (make) in
            make.top.equalTo(topImageView.snp.bottom).offset(45*_kScreenWidth)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 442*_kScreenWidth))
        }
        
        let topLabel = UILabel()
        topLabel.text = XALanguageManager.getString(key: "绑定谷歌身份验证器")
        topLabel.textAlignment = .center
        self.view.addSubview(topLabel)
        topLabel.font = UIFont.systemFont(ofSize: 15)
        topLabel.textAlignment = .center
        topLabel.textColor = UIColor("#418DFF")
        topLabel.font = UIFont.boldSystemFont(ofSize: 24)
        topLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(100*_kScreenWidth)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 24))
        }
        
        
        
        let titleLabel = UILabel()
        titleLabel.text = XALanguageManager.getString(key: "DKE官方提示\n为了您的财产安全，请妥善备份密钥以防遗失")
        titleLabel.textAlignment = .center
        self.view.addSubview(titleLabel)
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor("#FF2659")
        titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
        titleLabel.numberOfLines = 0
        titleLabel.sizeToFit()
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(topLabel).offset(50)
            make.centerX.equalTo(self.view)
            
            make.width.equalTo(330*_kScreenWidth)
//            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 24))
        }
        
        let codeLabel = UILabel()
        codeLabel.font = UIFont.boldSystemFont(ofSize: 39)
        codeLabel.text = ""
        codeLabel.textAlignment = .center
        self.view.addSubview(codeLabel)
        codeLabel.textColor = UIColor("#418DFF")
        codeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 0))
        }
        
        let copyBtn = UIButton()
        copyBtn.setTitle("", for: .normal)
        self.view.addSubview(copyBtn)
        copyBtn.backgroundColor = UIColor.clear
        copyBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeLabel.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 110, height: 0))
        }
        copyBtn.layer.cornerRadius = 5
        copyBtn.addTarget(self, action: #selector(TowCodeViewController.copyCode), for: .touchUpInside)
        
        let detailLabel = UILabel()
        detailLabel.text = ""
        self.view.addSubview(detailLabel)
        
        detailLabel.font = UIFont.systemFont(ofSize: 15)
        //        titleLabel.textAlignment = .center
        detailLabel.textColor = UIColor("#418DFF")
        detailLabel.numberOfLines = 0
        detailLabel.sizeToFit()
        detailLabel.font = UIFont.systemFont(ofSize: 14)
        detailLabel.snp.makeConstraints { (make) in
            make.top.equalTo(copyBtn.snp.bottom).offset(20*_kScreenWidth)
            make.centerX.equalTo(self.view)
            make.width.equalTo (280*_kScreenWidth)
            //            make.size.equalTo(CGSize(width: 300*_kScreenWidth, height: 17))
        }
        
        
        let codeImage = UIImageView()
        self.view.addSubview(codeImage)
        codeImage.snp.makeConstraints { (make) in
            make.top.equalTo(detailLabel.snp.bottom).offset(0)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 200*_kScreenWidth, height: 200*_kScreenWidth))
        }
        
        let url = self.myCode;
        //你的头像（可以为nil）
        let headerImage = UIImage(named: "")
        //生成图片并且显示
        codeImage.image = setupQRCodeImage(url!, image: headerImage)
        
        let backView = UIView()
        self.view.addSubview(backView)
        
        
        let bottomButton = UIButton(type: UIButtonType.system)
        
        bottomButton.setTitle(XALanguageManager.getString(key: "|  复制"), for: .normal)
        
        self.view.addSubview(bottomButton)
        bottomButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        bottomButton.addTarget(self, action: #selector(self.copyCode), for: .touchUpInside)
    bottomButton.contentHorizontalAlignment = .left
        //bottomLabel.titleLabel.textColor = UIColor("909090")
        
        
        
        let bottomLabel = UILabel()
        bottomLabel.text = "111"
        self.view.addSubview(bottomLabel)
        bottomLabel.font = UIFont.systemFont(ofSize: 16)
        bottomLabel.textAlignment = .center
        bottomLabel.textColor = UIColor("909090")
        bottomLabel.sizeToFit()
        bottomLabel.snp.makeConstraints { (make) in
            make.top.equalTo(codeImage.snp.bottom).offset(50)
            make.centerX.equalTo(self.view).offset(-30)
            
                make.height.equalTo(17)
            
//            make.size.equalTo(CGSize(width: 330*_kScreenWidth, height: 17))
        }
        
        
        let array : Array = myCode.components(separatedBy: "=")
        bottomLabel.text = array[1]
        //   otpauth://totp/13934168538?secret=KRXLBAIZLZIAB7J2
        
        
        bottomButton.snp.makeConstraints { (make) in
            make.top.equalTo(codeImage.snp.bottom).offset(50)
            make.left.equalTo(bottomLabel.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 80, height: 17))
        }
        
        backView.backgroundColor = UIColor("#4D579A")
        backView.layer.cornerRadius = 10
        backView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.width.equalTo(280)
            make.height.equalTo(25)
            make.centerY.equalTo(bottomLabel)
        }
        backView.alpha = 0.6
        
        
        
    }
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 width: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    @objc func copyCode() {
        let array : Array = myCode.components(separatedBy: "=")
        
        
        UIPasteboard.general.string = array[1]
        
        SVProgressHUD.showSuccess(withStatus: XALanguageManager.getString(key: "复制成功"))
        SVProgressHUD.dismiss(withDelay: 0.5)
        
        
        
    }
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
